<?php

namespace App\Http\Controllers\Index;

use App\Http\Controllers\UploadController;
use App\Http\Controllers\WxController;
use App\Models\Article;
use App\Models\ArticleComment;
use App\Models\User;
use App\Utils\CodeUtil;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class IndexController extends Controller
{

    public function index(){
        $user = User::find($_COOKIE['username']);
        $list = Article::orderBy("id","desc")->get();
        return view('Index/index',["list"=>$list,"user"=>$user]);
    }

    public function getInfo(Request $request) {
        $id = $request->input("id");
        $list = Article::find($id);
        $list->increment('read');
        $comment = ArticleComment::where("article_id",$id)->orderBy("id","asc")->get();
        $list->comment_list = $comment;
        return view('Index/info',["list"=>$list]);
    }

    public function postInfo(Request $request) {
        $name = $request->input("name");
        if(empty($name))   return response()->json(['code'=> CodeUtil::API_ERROR,"msg"=> "回复内容不可为空!"]);
        $comment = new ArticleComment();
        $comment->name  = $name;
        $comment->user_id = $_COOKIE['username'];
        $comment->article_id = $request->input("id");
        $comment->save();
        return response()->json(['code'=> CodeUtil::SUCCESS,"msg"=> "回复成功!"]);

    }

    public function getComment() {
        return view('Index/comment');
    }

    public function postComment(Request $request) {
        $name = $request->input("name");
        $content = $request->input("content");
        $image = $request->input("image",[]);
        if(empty($name))   return response()->json(['code'=> CodeUtil::API_ERROR,"msg"=> "标题不可为空!"]);
        $user_id = $_COOKIE['username'];
        $article = new Article();
        $article->user_id = $user_id;
        $article->name = $name;
        $article->content = $content;
        $article->image = json_encode($image);
        $article->save();
        return response()->json(['code'=> CodeUtil::SUCCESS,"msg"=> "发布成功!"]);
    }




    public function postUpload(Request $request) {

        $upload = new UploadController();
        $result = $upload->upload($request,"Filedata");
        return response()->json($result);
    }
}
